package com.cn.yang.servlet;

import com.alibaba.fastjson.JSONObject;
import com.cn.yang.model.mainPage.HeadLinkModel;
import com.cn.yang.model.production.ProductClassifyModel;
import com.cn.yang.model.production.ProductModel;
import com.cn.yang.service.MainPageService;
import com.cn.yang.service.ProductService;
import com.cn.yang.service.impl.MainPageServiceImpl;
import com.cn.yang.service.impl.ProductServiceImpl;
import com.cn.yang.servlet.product.ProductClassifyServlet;
import com.cn.yang.util.PageUtil;
import com.cn.yang.util.SortUserUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/product")
public class ProductServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        //获得headLink的List。
        MainPageService headLink = new MainPageServiceImpl();
        List<HeadLinkModel> list = headLink.selectHeadLink();
        //===============================================================================
        //分类查询
        Integer classify;
        String a = req.getParameter("classify");
        if (a==null || a.equals(0)){
            classify = null;
        }else {
            classify = Integer.valueOf(a);
        }
        Integer pageNumber = (req.getParameter("pageNumber") == null ? 1 : Integer.valueOf(req.getParameter("pageNumber")));
        System.out.println("sss"+classify);
        ProductModel model = new ProductModel();
        SortUserUtil sortUserUtil = new SortUserUtil();
        PageUtil pageUtil = new PageUtil();
        pageUtil.setPageSize(8);
        pageUtil.setPageNumber(pageNumber);
        model.setClassify(classify);
        model.setSortUserUtil(sortUserUtil);
        model.setPageUtil(pageUtil);
        //全查询
        ProductService service = new ProductServiceImpl();
        List<ProductClassifyModel> productClassifylist = service.findClassify();
        List<ProductModel> productlist = service.findProduct(model);
        int countProduct = service.countProduct(model);
        
        int countPage =  (int)Math.ceil(countProduct/8.0);
        System.out.println(countPage);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list",list);
        jsonObject.put("productClassifylist",productClassifylist);
        jsonObject.put("productlist",productlist);
        jsonObject.put("countPage",countPage);
        resp.getWriter().println(jsonObject);
    }
}
